#pragma once
#include <iostream>
#include <memory>
#include "Epoller.hpp"
#include "Socket.hpp"
#include "common.hpp"
#include "Connection.hpp"
#include "Channel.hpp"
using namespace SocketMoudle;
class Listener : public Connection
{
public:
    Listener(int port = defaultport)
        : _ptr(std::make_unique<TcpSocket>()), _port(port)
    {
        _ptr->BuildTcpSocketMethod(_port);
        SetEvent(EPOLLIN | EPOLLET); // ET模式
        SetNoBlock(_ptr->Fd());
    }
    void Recver() override
    {
        // accept
        InetAddr client;
        while (true)
        {
            int sockfd = _ptr->Accept(&client);
            if (sockfd == ACCEPT_ERR)
                break;
            else if (sockfd == ACCEPT_CONTINUE)
                continue;
            else if (sockfd == ACCEPT_DONE)
                break;
            else
            {
                std::shared_ptr<Connection> con=std::make_shared<Channel>(sockfd,client);
                con->SetEvent(EPOLLIN|EPOLLET);
                if(_handler!=nullptr)
                {
                    con->RegisterHandler(_handler);
                }
                GetOwner()->AddConnection(con);
            }
        }
    }
    void Sender() override
    {
    }
    void Excepter() override
    {
    }
    int GetFd() override
    {
        return _ptr->Fd();
    }
    ~Listener() 
    {
    }

private:
    std::unique_ptr<Socket> _ptr;
    int _port;
};